/*
 * @Descripttion:
 * @LastEditors: chen.long
 * @LastEditTime: 2024-02-24 14:55:14
 */
import { cacheOptions } from '../types/index.type';
import YbMicro from '../modules/sandbox';
export interface SandboxCache {
  ybmicro?: YbMicro;
  options?: cacheOptions;
}

export type appAddEventListenerOptions = AddEventListenerOptions & {
  targetWindow?: Window;
};

// 全部无界实例和配置存储map
export const idToSandboxCacheMap = (
  window.__POWERED_BY_YBMICRO__
    ? window.__YBMICRO.inject.idToSandboxMap
    : new Map<String, SandboxCache>()
) as Map<String, SandboxCache>;

export function getYbMicroById(id: String) {
  return idToSandboxCacheMap.get(id)?.ybmicro || null;
}

export function addSandboxCacheWithOptions(
  id: string,
  options: cacheOptions
): void {
  const ybMicroCache = idToSandboxCacheMap.get(id);
  if (ybMicroCache) idToSandboxCacheMap.set(id, { ...ybMicroCache, options });
  else idToSandboxCacheMap.set(id, { options });
}

export function deleteYbMicroById(id: string) {
  const ybMicroCache = idToSandboxCacheMap.get(id);
  if (ybMicroCache?.options)
    idToSandboxCacheMap.set(id, { options: ybMicroCache.options });
  idToSandboxCacheMap.delete(id);
}

export function getOptionsById(id: String): cacheOptions | null {
  return idToSandboxCacheMap.get(id)?.options || null;
}

export function addSandboxCacheWithYbMicro(id: string, sandbox: YbMicro): void {
  const ybmicroCache = idToSandboxCacheMap.get(id);
  if (ybmicroCache)
    idToSandboxCacheMap.set(id, { ...ybmicroCache, ybmicro: sandbox });
  else idToSandboxCacheMap.set(id, { ybmicro: sandbox });
}
